const db = uniCloud.database();
const uniID = require('uni-id-common');

exports.main = async (event, context) => {
  const uniIDIns = uniID.createInstance({ context });
  let body = event;
  if (event.body != undefined) {
    body = JSON.parse(event.body);
  }
  
  try {
    // 校验 token 获取 uid
    const { uid } = await uniIDIns.checkToken(body.uniIdToken);
	console.log(body.uniIdToken)
	console.log(await uniIDIns.checkToken(body.uniIdToken))
    if (!uid) {
      return { code: 403, msg: "身份验证失败" };
    }

    // 根据 uid 查找用户的 openid
    const userResult = await db.collection('uni-id-users').where({ _id: uid }).get();
	console.log('userresult',userResult)
    const user = userResult.data[0];  

    const openid = user.wx_openid?.mp;
	
	if (!user || !user.wx_openid?.mp) {
	  return { code: 404, msg: "未找到用户的 openid" };
	}

	console.log('openid',openid)
    return { code: 0, msg: "获取 openid 成功", openid };
  } catch (error) {
    console.error("云函数异常:", error);
    return { code: -500, msg: "云函数异常" };
  }
};
